package com.dk.controller;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.dk.VO.TbUserVO;
import com.dk.enums.ResultEnum;
import com.dk.pojo.TbUser;
import com.dk.result.Result;
import com.dk.service.TbUserService;
import com.dk.shiro.ShiroUtils;
import com.dk.util.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("userlogin")
@RefreshScope      //自动刷新配置, nacos的
@Api
@ApiOperation("登录接口")
public class TbUserLoginController {
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private TbUserService userService;

    //登录
    @PostMapping("login")
    @ApiOperation(value = "登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name="username",value = "用户名", paramType = "query"),
            @ApiImplicitParam(name="password",value = "密码", paramType = "query")
    })
    public Result login(@RequestParam String username, @RequestParam String password){

        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token1 = new UsernamePasswordToken(username,password);
        try{
            subject.login(token1);

        }catch (UnknownAccountException ue){
            return Result.respones(ResultEnum.FETCH_USERINFO_ERROR);
        }catch (IncorrectCredentialsException ce){
            return Result.respones(ResultEnum.PWD_ER);
        }

        TbUserVO vo = new TbUserVO();
        vo.setUsername(username);
        vo.setPassword(password);
        TbUser user = userService.selectByUsername(username);
        vo.setUserid(user.getUserid());
        vo.setPhone(user.getPhone());
        vo.setEmail(user.getEmail());
        vo.setSalt(user.getSalt());
        vo.setStatus(user.getStatus()); //vo.getUserid()

        String token = jwtUtil.createJwt(String.valueOf(vo.getUserid()), JSONObject.toJSONString(vo), "role");
        return Result.OK().setData(token);
    }

    @Resource
    private JavaMailSenderImpl javaMailSender;

    @Value("771452613@qq.com")
    private String sender;

    //忘记密码
    @PostMapping("recoverPwd")
    @ApiOperation(value = "忘记密码")
    @ApiImplicitParam(name="username",value = "用户名",required = true, paramType = "query")
    public Result recoverPwd(@RequestParam String username){
        //1.根据输入的用户名查询出用户注册时候的邮箱
        TbUser tbUser = userService.selectByUsername(username);
        if(tbUser == null){
            return Result.respones(ResultEnum.FETCH_USERINFO_ERROR);
        }
        //2.系统生成随机的密码
        String salt = ShiroUtils.generateSalt(6);
        String randomPwd = RandomUtil.randomString(4);
        String pwd = ShiroUtils.encryptPassword("MD5", randomPwd, salt, 3);

        tbUser.setSalt(salt);
        tbUser.setPassword(pwd);
        userService.updateByName(tbUser);
        //3.然后发送到用户的邮箱，用户通过登录邮箱找回密码
        String email = tbUser.getEmail();
        SimpleMailMessage message = new SimpleMailMessage();
        //设置主题
        message.setSubject("新密码");
        //设置内容
        message.setText(randomPwd);
        //收件人
        message.setTo(email);
        //发件人
        message.setFrom(sender);
        //开始发送
        javaMailSender.send(message);
        return Result.OK();
    }
}
